import os
import subprocess

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from database import get_db
from model.cname import CName
from model.cdn_node import CdnNode
from schema.cname_schema import CNameCreate, CNameUpdate, CNameOut
from services import cname
from config import settings


import logging
logger = logging.getLogger("fast-run")

from route.user_api import get_current_user

router = APIRouter(tags=["cname"],
                   dependencies=[Depends(get_current_user)]  # 🔑 所有路由都需要认证
                   )
@router.post("", response_model=CNameOut)
def create_a_record(record: CNameCreate, db: Session = Depends(get_db)):
    # 检查节点ID是否存在
    nodes = db.query(CdnNode).filter(CdnNode.id.in_(record.node_ids)).all()
    if len(nodes) != len(record.node_ids):
        raise HTTPException(status_code=400, detail="部分节点ID不存在")

    return cname.create_a_record(db, record)

@router.get("/{record_id}", response_model=CNameOut)
def read_a_record(record_id: int, db: Session = Depends(get_db)):
    db_record = cname.get_a_record(db, record_id)
    if not db_record:
        raise HTTPException(status_code=404, detail="Record not found")
    return db_record

@router.get("", response_model=list[CNameOut])
def read_a_records(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return cname.get_a_records(db, skip=skip, limit=limit)

# TODO 返回422
@router.get("/online", response_model=list[CNameOut])
def get_online(db: Session = Depends(get_db)):
    return cname.get_online(db)
@router.put("/{record_id}", response_model=CNameOut)
def update_a_record(record_id: int, record: CNameUpdate, db: Session = Depends(get_db)):
    db_record = cname.update_a_record(db, record_id, record)
    if not db_record:
        raise HTTPException(status_code=404, detail="Record not found")
    return db_record

@router.delete("/{record_id}", response_model=CNameOut)
def delete_a_record(record_id: int, db: Session = Depends(get_db)):
    # 先查记录，拿到 domain
    db_record = cname.get_a_record(db, record_id)
    if not db_record:
        raise HTTPException(status_code=404, detail="Record not found")

    domain = db_record.domain

    # 删除数据库中的记录
    deleted = cname.delete_a_record(db, record_id)

    # 从 Corefile 删除对应配置
    cname.remove_domain_from_corefile(domain, f"{settings.COREDNS_CONF_PATH}/Corefile")

    cname.restart_coredns()

    return deleted

@router.post("/offline/{record_id}", response_model=CNameOut)
def offline_a_record(record_id: int, db: Session = Depends(get_db)):
    """
    下线记录（将 status 设为 False）
    :param record_id:
    :param db:
    :return:
    """
    # 先查记录
    db_record = cname.get_a_record(db, record_id)
    if not db_record:
        raise HTTPException(status_code=404, detail="Record not found")

    # 修改状态为 False
    db_record.status = False
    db.commit()
    db.refresh(db_record)

    # 从 Corefile 删除对应配置
    cname.remove_domain_from_corefile(db_record.domain, f"{settings.COREDNS_CONF_PATH}/Corefile")

    cname.restart_coredns()

    return db_record


@router.post("/deploy/{record_id}")
def deploy_record(record_id: int, db: Session = Depends(get_db)):
    # 查询 CName
    record = db.query(CName).filter(CName.id == record_id).first()
    if not record:
        raise HTTPException(status_code=404, detail="Record not found")

    # zone 和 corefile 路径
    zone_path = f"{settings.COREDNS_CONF_PATH}/zones/{record.domain}.zone"
    corefile_path = f"{settings.COREDNS_CONF_PATH}/Corefile"

    # 生成 zone 文件
    zone_content = cname.generate_zone_file(record.domain, record.nodes)
    logger.info(f"=============zone file content============ \n {zone_content}  \n ==============zone file content end===============")

    os.makedirs(os.path.dirname(zone_path), exist_ok=True)
    with open(zone_path, "w") as f:
        f.write(zone_content)

    # 更新 Corefile
    cname.update_corefile(record.domain, zone_path, corefile_path)
    print("Corefile 和 zone 文件已写入完成！")

    # 重启 CoreDNS 服务
    cname.restart_coredns()

    # ✅ 部署完成后更新状态
    record.status = True
    db.commit()
    db.refresh(record)

    return {"message": f"{record.domain} deployed to {len(record.nodes)} nodes", "record": record}
